<template>
  <div class="pages" v-loading="loading">
    <div class="tabsBox">
      <el-tabs
        v-model="editableTabsValue"
        type="card"
        closable
        @tab-remove="removeTab"
        @tab-click="clickTab"
      >
        <el-tab-pane
          v-for="(item, index) in editableTabs"
          :key="index"
          :label="item.title"
          :name="item.name"
        >
          <!--添加课程表 课程表列表 -->
          <div v-if="dialogVisible" class="tableList">
            <div class="create">
              <el-button type="primary" @click="createClick"
                >新建{{ dialogVisible ? "课程" : "排课" }}表</el-button
              >
            </div>
            <el-table :data="queryClassList">
              <el-table-column
                prop="teacherName"
                label="讲师名称"
              ></el-table-column>
              <el-table-column
                prop="trainingPeriods"
                label="讲师期次"
              ></el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
              ></el-table-column>
              <el-table-column
                prop="createUser"
                label="创建人"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" @click.native="editFn(scope.row)"
                    >修改</el-button
                  >
                  <el-button type="danger" @click.native="deleteFn(scope.row)"
                    >删除</el-button
                  >
                </template></el-table-column
              >
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 课程表列表 -->
    <div v-if="!dialogVisible">
      <div class="create">
        <el-button type="primary" @click="createClick"
          >新建{{ dialogVisible ? "课程" : "排课" }}表</el-button
        >
      </div>
      <div class="crm-container">
        <el-table
          id="crm-table"
          :row-height="40"
          :data="list"
          :height="tableHeight"
          :cell-class-name="cellClassName"
          :header-cell-class-name="headerCellClassName"
          use-virtual
          class="n-table--border"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column label="名称" prop="className">
            <template slot-scope="scope">
              <span class="title" @click="clickShowTable(scope.row)">{{
                scope.row.className
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="classTime" label="课程时间">
            <template slot-scope="scope">
              {{ scope.row.classTime || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column prop="createUser" label="创建人"> </el-table-column>
          <el-table-column
            :resizable="false"
            label="操作"
            fixed="right"
            width="300"
          >
            <template slot-scope="scope">
              <el-button type="primary" @click.native="addFn(scope.row)"
                >添加课程表</el-button
              >
              <el-button type="primary" @click.native="bianjiFn(scope.row)"
                >编辑</el-button
              >
              <el-button type="danger" @click.native="deleteFn(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="p-contianer">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            class="p-bar"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
          />
        </div> -->
      </div>
    </div>
    <!-- 新建排课表 -->
    <el-dialog
      :title="classTitle"
      :visible.sync="isCreate"
      width="30%"
      :before-close="handleCloseCreate"
    >
      <div class="createInput">
        <p>排课表名称</p>
        <el-input
          type="text"
          placeholder="请输入内容"
          v-model="className"
          maxlength="15"
          show-word-limit
        >
        </el-input>
      </div>
      <div class="createInput">
        <p>排课表时间</p>
        <el-date-picker
          v-model="classTime"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择月份"
          @change="changeDate"
        >
        </el-date-picker>
      </div>
      <div class="createBtn">
        <el-button @click="handleCloseCreate">取消</el-button>
        <el-button type="primary" @click="addClassName">确认</el-button>
      </div>
    </el-dialog>
    <!-- 新建课程表 -->
    <el-dialog
      :title="title"
      :visible.sync="isCreateCourse"
      width="30%"
      :before-close="handleClosekecheng"
    >
      <div class="createInput">
        <p>课程讲师</p>
        <xh-user-cell
          :value="user"
          :teacherId="teacherId"
          :isTeacher="true"
          @value-change="userSelect"
          style="width: 100%"
          ref="xh_UserCell"
        />
      </div>
      <div class="createInput">
        <p>课程期次</p>
        <el-input
          type="text"
          placeholder="请输入期次"
          v-model="trainingPeriods"
        >
        </el-input>
      </div>
      <span class="tip">使用英文 “逗号” 隔开 “,”</span>
      <div class="createBtn">
        <el-button @click="handleClosekecheng">取消</el-button>
        <el-button type="primary" @click="addKechengName">确认</el-button>
      </div>
    </el-dialog>
    <!-- 查看课程表 -->
    <el-dialog
      title="查看课程表"
      :visible.sync="showTable"
      width="30%"
      :before-close="handleCloseshowTable"
    >
      <el-table :data="queryClassList">
        <el-table-column label="序号" type="index" width=""></el-table-column>
        <el-table-column
          prop="teacherName"
          label="讲师名称"
          width=""
        ></el-table-column>
        <el-table-column
          prop="trainingPeriods"
          label="排课期次"
          width=""
        ></el-table-column>
      </el-table>
      <div class="createBtn">
        <el-button @click="showTable = false" type="primary">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryList,
  addTimeTable,
  deleteById,
  queryByClassId,
  addData,
  deleteData,
  updateData,
  updateClassName,
} from "@/api/crm/timeTable";

import { XhUserCell } from "@/components/CreateCom";
import { mapGetters } from "vuex";
export default {
  name: "timetable",
  components: {
    XhUserCell,
  },
  props: {},
  data() {
    return {
      editableTabsValue: "1",
      editableTabs: [
        // {
        //   title: "排课表",
        //   name: "1",
        //   content: "Tab 1 content",
        // },
      ],
      tabIndex: 2,

      title: "新建课程表",
      classTitle: "新建排课表",
      loading: false,
      crmType: "timetable",
      dialogVisible: false,
      tableHeight: document.documentElement.clientHeight - 235, // 表的高度
      className: "", // 课表名称
      classTime: "", //课程月份
      classId: "",
      showTable: false, //查看课程表
      queryClassList: [], // 课程列表
      isCreate: false, //新建排课弹窗
      isCreateCourse: false, //新建课程弹窗
      list: [],
      user: [],
      teacherId: "",
      trainingPeriods: "",
      rowId: "",
      isEdit: false, //判断是否修改
      editId: "",
      classNameedit: false,

      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      myInterval: "",
      selectData: [],
    };
  },
  computed: {
    ...mapGetters(["crm", "userInfo"]),
  },
  watch: {},
  created() {
    // 控制table的高度
    window.onresize = () => {
      this.updateTableHeight();
    };
  },

  beforeDestroy() {},
  mounted() {
    this.getList();
  },
  methods: {
    // 标签点击
    clickTab(e) {
      // if (e.index == 0) {
      //   this.dialogVisible = false;
      // }
      // if (e.index == 1) {
      //   this.dialogVisible = true;
      // }
    },
    //移除标签
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.dialogVisible = false;
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
    },
    changeDate(val) {
      console.log(val);
    },
    //新增课程表关闭
    handleClosekecheng() {
      this.isCreateCourse = false;
      this.$refs.xh_UserCell.checkUsers([]);
      this.teacherId = "";
      this.trainingPeriods = "";
    },
    //新增排课表点击按钮
    handleCloseCreate() {
      this.isCreate = false;
      this.className = "";
    },
    //新增课程确认
    addKechengName() {
      if (this.teacherId == "") {
        this.$message.error("请选择讲师");
        return;
      }
      if (this.trainingPeriods == "") {
        this.$message.error("请输入期次");
        return;
      }
      if (this.isEdit) {
        this.getupdateData();
      } else {
        this.getaddData();
      }
    },
    getaddData() {
      this.loading = true;
      addData({
        classId: this.rowId,
        teacherId: this.teacherId,
        trainingPeriods: this.trainingPeriods,
      })
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.isCreateCourse = false;
            this.teacherId = "";
            this.trainingPeriods = "";
            this.$refs.xh_UserCell.checkUsers([]);
            this.$message.success("添加成功");
            this.getqueryByClass(this.rowId);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 编辑课程排期名称
    bianjiFn(item) {
      this.className = item.className;
      this.classTime = item.classTime;
      this.classId = item.id;
      this.classTitle = "编辑排课表";
      this.isCreate = true;
    },
    //修改按钮点击
    editFn(item) {
      this.isEdit = true;
      this.title = "编辑课程表";
      this.editId = item.id;
      this.teacherId = item.teacherId;
      this.trainingPeriods = item.trainingPeriods;
      this.isCreateCourse = true;
      this.myInterval = setInterval(() => {
        this.$refs.xh_UserCell.bianji(item);
        clearInterval(this.myInterval);
        this.myInterval = null;
      }, 500);
    },
    getupdateData() {
      this.loading = true;
      let teacherId = "";
      if (this.selectData.length > 0) {
        teacherId = this.teacherId;
      } else {
        teacherId = "";
      }
      updateData({
        id: this.editId,
        classId: this.rowId,
        teacherId: teacherId,
        trainingPeriods: this.trainingPeriods,
      })
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.$message.success("修改成功");
            this.$refs.xh_UserCell.checkUsers([]);
            this.isCreateCourse = false;
            this.teacherId = "";
            this.trainingPeriods = "";
            this.getqueryByClass(this.rowId);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 选择课程讲师
    userSelect(data) {
      this.selectData = data.value;
      if (data.value.length > 0) {
        this.teacherId = data.value[0].userId;
      } else {
        this.teacherId = "";
      }
    },
    //新增排课表
    addClassName() {
      if (this.className == "") {
        this.$message.error("请输入名称");
        return;
      }
      if (this.classTime == "") {
        this.$message.error("请选择月份");
        return;
      }
      if (this.classId) {
        this.getUpdateClassName();
      } else {
        this.getAddTimeTable();
      }
    },
    //添加课程
    getAddTimeTable() {
      addTimeTable({
        className: this.className,
        classTime: this.classTime,
      })
        .then((res) => {
          if (res.code == 0) {
            this.isCreate = false;
            this.className = "";
            this.classTime = "";
            this.$message.success("添加成功");
            this.getList();
          }
        })
        .catch(() => {});
    },
    //修改课程名称
    getUpdateClassName() {
      updateClassName({
        id: this.classId,
        className: this.className,
        classTime: this.classTime,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("保存成功");
            this.getList();
            this.className = "";
            this.isCreate = false;
          }
        })
        .catch(() => {});
    },
    //查看课程表
    handleCloseshowTable() {
      this.showTable = false;
    },
    // 点击查看课程列表
    clickShowTable(item) {
      this.getqueryByClass(item.id);
      this.showTable = true;
    },
    // 课程列表
    getqueryByClass(id) {
      this.loading = true;
      queryByClassId({
        id: id,
      })
        .then((res) => {
          if (res.code == 0) {
            this.queryClassList = res.data;
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 点击添加课程表按钮
    addFn(item) {
      let newTabName = ++this.tabIndex + "";
      this.editableTabs.push({
        title: "添加课程表",
        name: newTabName,
        content: "New Tab content",
      });
      this.editableTabsValue = newTabName;
      this.dialogVisible = true;
      this.rowId = item.id;
      this.getqueryByClass(item.id);
    },

    // 删除
    deleteFn(item) {
      this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.dialogVisible) {
            this.getdeleteData(item.id);
          } else {
            this.getdeleteById(item.id);
          }
        })
        .catch(() => {});
    },
    getdeleteById(id) {
      this.loading = true;
      deleteById({
        id: id,
      })
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.$message.success("删除成功");
            this.getList();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getdeleteData(id) {
      this.loading = true;
      deleteData({
        id: id,
      })
        .then((res) => {
          if (res.code == 0) {
            this.loading = false;
            this.$message.success("删除成功");
            this.getqueryByClass(this.rowId);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      queryList()
        .then((res) => {
          if (res.code == 0) {
            this.list = res.data;
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "invoiceApplyNumber") {
        return "can-visit--underline can-visit--bold";
      } else {
        return "";
      }
      //  else if (
      //   column.property === 'customerName' ||
      //   column.property === 'contractNum'
      // ) {
      //   return 'can-visit--underline'
      // }
    },

    headerCellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "invoiceApplyNumber") {
        return "header-can-visit-backgroud";
      }
      return "";
    },

    /**
     * 创建点击
     */
    createClick() {
      this.isEdit = false;
      this.classId = "";
      this.title = "新建课程表";
      this.classTitle = "新建排课表";
      if (!this.dialogVisible) {
        this.isCreate = true;
      } else {
        this.isCreateCourse = true;
      }
    },
    /**
     * 更新表高
     */
    updateTableHeight() {
      var offsetHei = document.documentElement.clientHeight;
      var removeHeight = 0;

      if (
        this.filterObj &&
        this.filterObj.obj &&
        this.filterObj.obj.length > 0
      ) {
        removeHeight = 285;
      } else {
        removeHeight = 235;
      }
      this.tableHeight = offsetHei - removeHeight;
    },
  },
  // 销毁定时器
  beforeDestroy() {
    clearInterval(this.myInterval);
    this.myInterval = null;
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px 20px;
}
.create {
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 80px;
  padding-bottom: 20px;
}
.createInput {
  display: flex;
  align-items: center;
  margin-bottom: 22px;
  p {
    width: 115px;
    font-size: 16px;
  }
}
.tip {
  font-size: 13px;
  color: red;
  padding-left: 96px;
}
.createBtn {
  display: flex;
  justify-content: end;
  margin-top: 40px;
}
.title {
  cursor: pointer;
  &:hover {
    color: #2362fb;
    border-bottom: 1px solid;
  }
}
.tableList {
  .handleClose {
    font-size: 24px;
    display: flex;
    justify-content: end;
    padding-bottom: 20px;
    i {
      cursor: pointer;
      &:hover {
        color: #2362fb;
      }
    }
  }
}
.tabsBox {
  background: #fff;
}
</style>
